package com.lam.system.controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.write.handler.WriteHandler;
import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.components.easyexcel.export.DownloadUtil;
import com.lam.common.components.easyexcel.imp.ImportUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.framework.operLog.enums.LogSave;
import com.lam.framework.security.PermissionUtil;
import com.lam.system.entity.SysUser;
import com.lam.system.entity.imp.SysUserImp;
import com.lam.system.listener.UploadSysUserListener;
import com.lam.system.param.SysUserParam;
import com.lam.system.service.SysUserService;

/**
 * 用户信息Controller
 * 
 * @author admin
 * @date 2022-09-20
 */
@Log(title = "用户信息")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询用户信息列表
     */
    @Log(oper="分页查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('sys:user:list')")
    @GetMapping("/list")
    public Result list(SysUserParam param) {
    
        startPage();
        List<SysUser> list = sysUserService.selectList(param);
        return Result.ok(getTableData(list));
    }
    
    /**
     * 查询用户列表
     */
    @Log(oper="候选列表查询")
    @DictAutoTransfer
//    @PreAuthorize("@ss.hasPm('sys:user:toSelectList')")
    @GetMapping("/toSelectList")
    public Result toSelectList(SysUserParam param) {
    	
    	ValidateUtil.validRequired(param.getSelectType(), "selectType不能为空！");
    	
    	PermissionUtil.hasPm("sys:user:toSelectList:" + param.getSelectType());
    	
    	switch (param.getSelectType()) {
    	//角色下的用户
		case "roleUser": 
		//角色添加用户的候选列表
		case "roleToSelectUser": ValidateUtil.validRequired(param.getRoleId(), "roleId不能为空！");break;
		
		//组织机构下的用户
		case "deptUser": 
		//组织机构添加用户的候选列表
		case "deptToSelectUser": ValidateUtil.validRequired(param.getDeptId(), "deptId不能为空！");break;

		default:
			return Result.fail("未知的selectType！");
		}
    
        startPage();
        List<SysUser> list = sysUserService.toSelectList(param);
        return Result.ok(getTableData(list));
    }
    
    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPm('sys:user:export')")
    @Log(businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public Result export(SysUserParam param) {
    
        withOrderBy();
        List<SysUser> list = sysUserService.selectList(param);
        return Result.ok(DownloadUtil.exportExcel("用户信息导出", list, SysUser.class));
    }
    
    @Log(businessType = BusinessType.EXPORT, oper = "下载导入模板")
    @PreAuthorize("@ss.hasPm('sys:user:import')")
    @GetMapping("/downloadTemplate")
    public Result downloadTemplate() {
        WriteHandler headRowCommentWriteHandler = ImportUtil.getHeadRowCommentWriteHandler(SysUserImp.class, SysUser.class, Add.class);
        WriteHandler dropDownWriteHandler = ImportUtil.getDropDownWriteHandler(SysUserImp.class, Add.class);
        return Result.ok(DownloadUtil.exportExcel("用户信息导入模板", Collections.emptyList(), SysUserImp.class, 
            headRowCommentWriteHandler, dropDownWriteHandler));
    }
    
    @Log(businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPm('sys:user:import')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file, boolean updateSupport) {
        
        logger.info("用户信息数据导入, 开始接收文件数据...");
        UploadSysUserListener readListener = new UploadSysUserListener(sysUserService);
        readListener.setUpdateSupport(updateSupport);
        ImportUtil.importData("用户信息", file, readListener);
        Map<String, Object> data = readListener.getOperResult();
        data.put("originalFilename", file.getOriginalFilename());
        return Result.ok(data);
    }
    
    /**
     * 获取用户信息详细信息
     */
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('sys:user:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
        return Result.ok(sysUserService.selectByIdWithDept(id));
    }
    
    /**
     * 判断用户名是否存在
     */
    @PreAuthorize("@ss.hasPm('sys:user:add')")
    @Log(oper="校验用户名是否存在", businessType = BusinessType.CHECK_UNIQUE, logSave = LogSave.YES)
	@GetMapping("/chkUq/{username}")
    public Result checkUnique(@PathVariable("username") String username) {
    
        return Result.ok().data(ValidateUtil.validUnique(sysUserService.selectByUsername(username)));
    }
    
    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPm('sys:user:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody SysUser sysUser) {
    
    	ValidateUtil.validUniqueWithExp(sysUserService.selectByUsername(sysUser.getUsername()), "登录账号已存在！");
    	
        return toAjax(sysUserService.insert(sysUser));
    }
    
    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPm('sys:user:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody SysUser sysUser) {
    
        return toAjax(sysUserService.update(sysUser));
    }
    
    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPm('sys:user:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(sysUserService.deleteById(id));
    }
    
    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPm('sys:user:resetPwd')")
    @Log(businessType = BusinessType.UPDATE, oper = "重置密码")
    @PostMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUserParam param) {
    	
    	ValidateUtil.validRequired(param.getId(), "id不能为空！");
    	
    	return toAjax(sysUserService.resetPwd(param));
    }

}
